package com.blog.utils;
import com.blog.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.UUID;

@Component
public class MinioUtil {
    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioConfig minioConfig;

    public String upload(MultipartFile file) throws  Exception {
        LocalDateTime today = LocalDateTime.now();
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String filename = today.getMonth().getValue() + "/" +  today.getDayOfMonth()
                + "/" +  UUID.randomUUID().toString().replace("-", "").substring(0, 8)
                + "_"
                + FilenameUtils.getBaseName(file.getOriginalFilename())
                + (extension.isEmpty() ? "" : "." + extension);;

        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(minioConfig.getBucketName())
                        .object(filename)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        return minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + filename;
    }


}
